<template>
  <el-row>
    <el-col :span="12">
      <el-form ref="userAddForm" :model="form" :rules="rules">
        <el-form-item label="账号" prop="name">
          <el-input v-model="form.name" type="text"/>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" type="password"/>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="form.confirmPassword" type="password"/>
        </el-form-item>
        <el-form-item>
          <el-button @click="save"> 保存</el-button>
          <el-button @click="complete(false)"> 取消</el-button>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>

<script>
import userApi from '@/api/sys/user'

export default {
  name: 'UserAdd',
  data() {
    // 验证-密码
    var validatePass = (rule, value, callback) => {
      if (this.form.confirmPassword !== '') {
        this.$refs.userAddForm.validateField('confirmPassword')
      }
      callback()
    }
    // 验证-确认密码
    var validateConfirmPass = (rule, value, callback) => {
      if (value !== this.form.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      // 表单数据
      form: {
        name: '',
        password: '',
        confirmPassword: ''
      },
      // 验证规则
      rules: {
        name: [
          { required: true, message: '不能为空', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在3到20个字符之间', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '不能为空', trigger: 'blur' },
          { min: 6, max: 20, message: '长度在3到20个字符之间', trigger: 'blur' },
          { validator: validatePass, trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '不能为空', trigger: 'blur' },
          { min: 6, max: 20, message: '长度在3到20个字符之间', trigger: 'blur' },
          { validator: validateConfirmPass, trigger: 'blur' }
        ]

      }
    }
  },
  methods: {
    save() {
      // 验证表单数据
      this.$refs.userAddForm.validate((valid) => {
        if (valid) {
          // 验证通过，提交数据
          userApi.addUser(this.form).then(response => {
            if (response.data.code === 200) {
              this.$message.success('保存成功')
              this.complete(true)
            } else {
              this.$message.error(response.data.msg)
            }
          })
        }
      })
      return
    },
    complete(done) {
      // this.closeCurrentTag()
      // this.toList()
      this.$refs['userAddForm'].resetFields()
      this.$emit('complete', done)
    }
  }
}
</script>

